package com.sharding.order.service.merchant.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sharding.order.common.enums.OrderEnums;
import com.sharding.order.common.enums.OrderOperateType;
import com.sharding.order.common.enums.RequestSource;
import com.sharding.order.common.mq.RocketMQProducer;
import com.sharding.order.domain.convertor.OrderConvertor;
import com.sharding.order.domain.message.OrderSyncMessage;
import com.sharding.order.domain.query.MerchantOrderInfoQuery;
import com.sharding.order.domain.query.OrderInfoBaseQuery;
import com.sharding.order.domain.vo.MerchantOrderVO;
import com.sharding.order.domain.vo.OrderInfoVO;
import com.sharding.order.domain.vo.OrderDetailVO;
import com.sharding.order.repository.MerchantOrderRepository;
import com.sharding.order.service.merchant.MerchantOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author ruyuan
 */
@Slf4j
@Service
public class MerchantOrderServiceImpl implements MerchantOrderService {

    @Autowired
    private MerchantOrderRepository merchantOrderRepository;
    @Autowired
    private OrderConvertor orderConvertor;
    @Value(value = "${order.topic}")
    private String topic;
    @Autowired
    private RocketMQProducer rocketMQProducer;


    @Override
    public  Page<MerchantOrderVO> queryOrderInfoByMerchant(MerchantOrderInfoQuery merchantOrderInfoQuery) {
        //商户query转订单基础查询类
        OrderInfoBaseQuery orderInfoBaseQuery = orderConvertor.merchantQueryToBaseOrder(merchantOrderInfoQuery);
        //查询订单信息
        Page<OrderInfoVO> orderInfoVOPage = merchantOrderRepository.queryOrderInfoList(orderInfoBaseQuery);
        return orderConvertor.OrderVoToMerchantInfoVo(orderInfoVOPage);
    }

    @Override
    public OrderDetailVO getOrderDetail(String orderNo) {
        return merchantOrderRepository.getOrderDetail(orderNo);
    }

    @Override
    public void receiveOrder(String orderNo) {
        merchantOrderRepository.receiveOrder(orderNo, OrderEnums.RECEIVED_ORDER.getCode());
        //构建消息体
        OrderSyncMessage orderSyncMessage = OrderSyncMessage.builder()
                .requestSource(RequestSource.B)
                .orderOperateType(OrderOperateType.updateOrderStatus)
                .orderNo(orderNo)
                .build();
        //发送mq消息
        rocketMQProducer.reliablySend(topic, orderSyncMessage, orderSyncMessage.getOrderNo(), obj -> {
            OrderSyncMessage message = (OrderSyncMessage) obj;
            // 这里可以将消息存储到db，然后由后台线程定时重试，确保消息一定到达Broker
            log.info("receiveOrder send mq message failed, store the mq message to db，orderNo:[{}],message:[{}]",message.getOrderNo(),message);
        });
    }

}
